package com.example.bbook.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bbook.entity.UserEntity;
import com.example.bbook.mapper.UserMapper;
import com.example.bbook.util.Response;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;

/**
 * 自定义拦截器
 */
public class JWTSSOAuthConfig implements HandlerInterceptor {
    public UserMapper userMapper;
    JWTSSOAuthConfig(){

    }
    JWTSSOAuthConfig(UserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
          token = request.getParameter("token");
        }

        if (token != null && !token.equals("")) {
            QueryWrapper<UserEntity> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("auth", token);
            if(userMapper.selectOne(userQueryWrapper) != null) {
                return true;
            }
        }
        String jsonObjectStr = JSONObject.toJSONString(Response.noAuth());
        returnJson(response, jsonObjectStr);
        return false;
    }


    @SuppressWarnings("unused")
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (Exception e) {
            System.out.println("异常");
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
